package com.peak.distribution.jms.admin;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.peak.distribution.entity.admin.DisUser;
import com.peak.distribution.entity.admin.DisUserLoginLog;
import com.peak.distribution.manager.admin.DisUserLoginLogManager;
import com.peak.distribution.manager.admin.DisUserManager;
import com.peak.spring.boot.core.mapper.JsonMapper;
import com.peak.spring.boot.tools.Dates;

import lombok.extern.slf4j.Slf4j;

@Component
@Slf4j
@Transactional
public class UserLoginConsumer {
	
	@Autowired
	private DisUserLoginLogManager userLoginLogManager;
	
	@Autowired
	private DisUserManager userManager;
	
	@Autowired
	private PasswordEncoder passwordEncoder;
	
	/**
	 * 消费用户登录的消息
	 * @param json
	 */
	@JmsListener(destination = "${mq.queue.login.log}")
	public void receiveLoginQueue(String json) {
		log.info("接收用户登录消息：{}", json);
		// 把json数据转换成对象
		DisUserLoginLog log = JsonMapper.nonDefaultMapper().fromJson(json, DisUserLoginLog.class);
		// 设置当前时间
		log.setLoginTime(Dates.now());
		// 根据登录名查询是否存在用户
		DisUser user = userManager.getByUsername(log.getUsername());
		if (user != null) {// 如果能找到登录的用户
			//把用户的id写上去
			log.setUserId(user.getId());
			// 如果登录成功，更新用户的登录次数和上次登录的时间
			if (log.getStatus()) {
				// 登录成功的话，密码加密，数据库存明文不太好
				log.setPassword(passwordEncoder.encode(log.getPassword()));
				// 登录次数+1
				user.addLoginCount();
				// 登录时间更新
				user.setLastLoginDateTime(log.getLoginTime());
				// 保存用户
				userManager.save(user);
			}
		}
		// 新增登录日志
		userLoginLogManager.save(log);
	}
}
